package com.beyond.trace.controller;

import com.beyond.trace.domain.YieldConfigure;
import com.beyond.trace.requestVo.YieldConfigureReq;
import com.beyond.trace.service.YieldConfigureService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName: YieldConfigureController
 * @author: z越
 * @date: 2024/4/8  10:35
 * @description
 */
@RestController
@RequestMapping("/yield/configure")
@Api(tags = "产业产值配置")
@RequiredArgsConstructor
public class YieldConfigureController extends BaseController {
    private final YieldConfigureService yieldConfigureService;

    @GetMapping
    @ApiOperation("查询列表（分页）")
    public TableDataInfo page(){
        startPage();
        List<YieldConfigure> list = this.yieldConfigureService.list();
        return getDataTable(list);
    }

    @GetMapping("/list")
    @ApiOperation("查询列表")
    public AjaxResult list(){
        List<YieldConfigure> list = this.yieldConfigureService.list();
        return AjaxResult.success(list);
    }

    @GetMapping("/{id}")
    @ApiOperation("查询详情")
    public AjaxResult getInfo(@PathVariable Long id){
        return AjaxResult.success(this.yieldConfigureService.getById(id));
    }

    @PostMapping
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody YieldConfigureReq req){
        List<YieldConfigure> list = this.yieldConfigureService.list();
        int maxNum = 3;
        if (CollectionUtils.isNotEmpty(list)){
            if (list.size()==maxNum){
                return AjaxResult.error("仅支持上传3年的数据");
            }
            long count = list.stream().filter(s -> s.getYear().equals(req.getYear())).count();
            if (count != 0){
                return AjaxResult.error("当前年份已存在");
            }

        }
        YieldConfigure po = req.toPo();
        return AjaxResult.success(this.yieldConfigureService.save(po));
    }

    @PutMapping("/{id}")
    @ApiOperation("修改")
    public AjaxResult update(@PathVariable Long id,@RequestBody YieldConfigureReq req){
        YieldConfigure oldPo = this.yieldConfigureService.getById(id);
        if (Objects.isNull(oldPo)){
            return AjaxResult.error("未查询到相关数据，请核对后重新操作");
        }
        YieldConfigure old = req.toOld(oldPo);
        old.setId(id);
        return AjaxResult.success(this.yieldConfigureService.updateById(old));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除")
    public AjaxResult delete(@PathVariable Long id){
        return AjaxResult.success(this.yieldConfigureService.removeById(id));
    }

}
